package com.yesallchina.wxapp.officialaccount.utils;


import com.yesallchina.wxapp.officialaccount.api.beans.Message;
import com.yesallchina.wxapp.officialaccount.api.enums.MessageEventTypeEnum;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtils {

    public static String beanToXml(Object instance) {
        try {
            JAXBContext context = JAXBContext.newInstance(instance.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            StringWriter writer = new StringWriter();
            marshaller.marshal(instance, writer);
            return writer.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static <T extends Message> T xmlToMessageBean(String xml) {
        T bean = null;
        try {
            JAXBContext context = JAXBContext.newInstance(Message.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            Message message = (Message) unmarshaller.unmarshal(new StringReader(xml));

            Class clazz = MessageEventTypeEnum.getClass(message.getMsgType());
            context = JAXBContext.newInstance(Message.class, clazz);
            unmarshaller = context.createUnmarshaller();
            bean = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    public static <T> T xmlToBean(String xml, Class clazz) {
        T bean = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            bean = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    @SuppressWarnings("unchecked")
    public static Map<String, String> xmlToMap(String wxxml) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            Document doc = DocumentHelper.parseText(wxxml);
            Element root = doc.getRootElement();
            List<Element> elements = root.elements();
            for (Element e : elements) {
                map.put(e.getName(), e.getStringValue());
            }
        } catch (Exception e) {
            return map;
        }
        return map;
    }

    public static String mapToXml(Map<String, String> reply) {
        if (null == reply) {
            return null;
        }
        Document document = DocumentHelper.createDocument();
        /* document.setXMLEncoding("UTF-8"); */
        Element root = document.addElement("xml");

        for (Map.Entry<String, String> entry : reply.entrySet()) {
            Element e = root.addElement(entry.getKey());
            e.setText(entry.getValue());
        }

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        StringWriter sw = new StringWriter();
        XMLWriter xw = new XMLWriter(sw, format);
        xw.setEscapeText(false);

        try {
            xw.write(document);
            xw.flush();
            xw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sw.toString().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
    }

}
